package cn.wikiflyer.beikang.act.cart;

import java.lang.reflect.Type;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.wikiflyer.beikang.BaseActivity;
import cn.wikiflyer.beikang.IApplication;
import cn.wikiflyer.beikang.R;
import cn.wikiflyer.beikang.act.cart.bean.BKCartListBean;
import cn.wikiflyer.beikang.act.user.bean.BKAddressResultBean;
import cn.wikiflyer.beikang.act.user.bean.BKOrderInfoBean;
import cn.wikiflyer.beikang.bean.base.BKBaseBean;
import cn.wikiflyer.beikang.payali.PaymentObject;
import cn.wikiflyer.beikang.payali.PaymentObject.OnPayListener;
import cn.wikiflyer.beikang.paywx.PayWxObject;
import cn.wikiflyer.beikang.utils.AddressUtil;
import cn.wikiflyer.beikang.view.BannerPro;
import cn.wikiflyer.beikang.view.ViewWithRadio;
import cn.wk.libs4a.bean.IBaseBean;
import cn.wk.libs4a.net.WKAsyncTaskPro;
import cn.wk.libs4a.utils.L;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 购物车支付页面 OrderInfoAct.java
 */
public class OrderInfoAct extends BaseActivity {

	private BannerPro bannerPro;
	private ViewWithRadio radio1;
	private ViewWithRadio radio2;
	private ViewWithRadio radio3;
	private LinearLayout ll_content_item;
	private TextView tv_total;
	private TextView tv_name; // 收件人
	private TextView tv_address; // 收件地址
	private TextView tv_phone; // 收件人电话
	private String cartIds = "";
	private String addressId = ""; // 提交订单需要的参数
	private int payMode = 1; // 支付方式1、微信 2、支付宝 3、银联
	private TextView pay_submit;
	private IBaseBean<BKCartListBean> baseBean;
	private boolean isSelected = false;

	@Override
	protected void onResume() {
		super.onResume();
		if (isWXsuccess) {
			successActivity();
		}
		if (!isSelected) {
			// 初始化地址
			if (AddressData.getInstance(ctx).getListData() != null
					&& AddressData.getInstance(ctx).getListData().size() > 0) {
				selectMethod(AddressData.getInstance(ctx).getListData());
			} else {
				new GetAddressListTask(ctx);
			}
		}
	}

	@Override
	public void getIntentData(Bundle savedInstanceState) {
		super.getIntentData(savedInstanceState);
		baseBean = (IBaseBean<BKCartListBean>) getIntent()
				.getSerializableExtra("basebean");
	}

	@Override
	public void loadXml() {
		setContentView(R.layout.bk_act_order_info);
	}

	@Override
	public void init() {
		bannerPro = (BannerPro) findViewById(R.id.bannerPro);
		radio1 = (ViewWithRadio) findViewById(R.id.viewWithRadio1);
		radio2 = (ViewWithRadio) findViewById(R.id.viewWithRadio2);
		radio3 = (ViewWithRadio) findViewById(R.id.viewWithRadio3);

		if (IApplication.onlyAlipay) {
			radio2.setVisibility(View.GONE);
			radio3.setVisibility(View.GONE);
		}

		ll_content_item = (LinearLayout) findViewById(R.id.ll_content_item);
		tv_total = (TextView) findViewById(R.id.textView_total);
		tv_name = (TextView) findViewById(R.id.textView_username);
		tv_address = (TextView) findViewById(R.id.textView_address);
		tv_phone = (TextView) findViewById(R.id.textView_phone);
		pay_submit = (TextView) findViewById(R.id.pay_submit);
		radio1.setOnClickListener(new PayModeClickListener());
		radio2.setOnClickListener(new PayModeClickListener());
		radio3.setOnClickListener(new PayModeClickListener());
		pay_submit.setOnClickListener(new PayModeClickListener());

		bannerPro.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (AddressData.getInstance(ctx).getListData() == null
						|| AddressData.getInstance(ctx).getListData().size() <= 0) {
					Toast.makeText(ctx, "请先在个人中心，设置收货收货地址", Toast.LENGTH_SHORT)
							.show();
				} else {
					Intent intent = new Intent(ctx, UserAddressSelectAct.class);
					startActivityForResult(intent, 5);
				}
			}
		});
		radio1.setChecked(true);
		radio2.setChecked(false);

		initItem();
	}

	/**
	 * 加载每个商品信息
	 */
	private void initItem() {
		for (int i = 0; i < baseBean.data.list.size(); i++) {
			View view_item = LayoutInflater.from(ctx).inflate(
					R.layout.bk_act_order_info_item_lay, null);
			((TextView) view_item.findViewById(R.id.textView_name))
					.setText(baseBean.data.list.get(i).title);
			((TextView) view_item.findViewById(R.id.textView_price))
					.setText("￥" + baseBean.data.list.get(i).unit_price);
			((TextView) view_item.findViewById(R.id.textView_num)).setText("x"
					+ baseBean.data.list.get(i).countLocal);
			app().imageLoader.displayImage(baseBean.data.list.get(i).thumb,
					((ImageView) view_item.findViewById(R.id.imageView_logo)));
			ll_content_item.addView(view_item);
		}
		int cost = 0;
		for (int i = 0; i < baseBean.data.list.size(); i++) {
			if (i + 1 == baseBean.data.list.size()) {
				// cartIds += baseBean.data.list.get(i).catid + "";
				cartIds += baseBean.data.list.get(i).id + "";
			} else {
				// cartIds += baseBean.data.list.get(i).catid + ",";
				cartIds += baseBean.data.list.get(i).id + ",";
			}
			int c = baseBean.data.list.get(i).countLocal;
			int m = Integer.valueOf(baseBean.data.list.get(i).unit_price);
			cost += (c * m);
		}
		tv_total.setText("￥" + cost);
	}

	@Override
	public void setData() {
	}

	/**
	 * 点击支付方式点击事件：1、支付宝 2、微信 3、银联
	 */
	class PayModeClickListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.viewWithRadio1:
				payMode = 1;
				radio1.setChecked(true);
				radio2.setChecked(false);
				radio3.setChecked(false);
				break;
			case R.id.viewWithRadio2:
				payMode = 2;
				radio1.setChecked(false);
				radio2.setChecked(true);
				radio3.setChecked(false);
				break;
			case R.id.viewWithRadio3:
				payMode = 3;
				radio1.setChecked(false);
				radio2.setChecked(false);
				radio3.setChecked(true);
				break;
			case R.id.pay_submit:
				if (checkEmpty()) {
					new CommitOrderTask(ctx); // 支付流程 1、支付宝 2、微信
				}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 检查是否符合支付条件
	 */
	private boolean checkEmpty() {
		if (cartIds.isEmpty()) {
			Toast.makeText(ctx, "没有可支付商品", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (addressId.isEmpty()) {
			Toast.makeText(ctx, "请先设置收货地址", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	/**
	 * 设置默认收件人信息的方法
	 */
	private void defaultAddress(BKAddressResultBean addressResultBean) {
		tv_name.setText("" + addressResultBean.receiver);
		String str_address = new AddressUtil(ctx).matchAddress(
				addressResultBean.sheng, addressResultBean.shi,
				addressResultBean.qu);
		tv_address.setText(str_address + addressResultBean.address);
		tv_phone.setText("" + addressResultBean.phone);
		addressId = addressResultBean.id;
	}

	/**
	 * 提交订单接口
	 */
	class CommitOrderTask extends WKAsyncTaskPro {
		public CommitOrderTask(Context context) {
			super(context);
		}
		@Override
		protected String doInBackground(boolean... params) {
			L.wj("cartIds:" + cartIds);
			return app().net.postOrder("" + cartIds, "" + addressId,payMode);
		}
		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean<BKOrderInfoBean>>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean<BKOrderInfoBean> base = gson.fromJson(result.trim(), cvbType);
			if (base.status == 1) {
				payMethod(base);
			} else {
				Toast.makeText(ctx,base.status + " - " + base.info + " - " + base.data, 0).show();
			}
		}
	}

	/**
	 * 收货地址列表(获取默认的收货地址)
	 */
	class GetAddressListTask extends WKAsyncTaskPro {
		public GetAddressListTask(Context context) {
			super(context);
		}

		@Override
		protected String doInBackground(boolean... params) {
			return app().net.getAddressList();
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean<ArrayList<BKAddressResultBean>>>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean<ArrayList<BKAddressResultBean>> base = gson.fromJson(
					result, cvbType);
			AddressData.getInstance(ctx).setListData(base.data);
			selectMethod(base.data);
		}
	}

	/**
	 * 选取默认地址的方法
	 */
	private void selectMethod(ArrayList<BKAddressResultBean> addressListData) {
		if (addressListData == null || addressListData.size() <= 0) {
			Toast.makeText(ctx, "没有收货地址，请添加", Toast.LENGTH_SHORT).show();
			return;
		}
		BKAddressResultBean defaultBean = null;
		for (int i = 0; i < addressListData.size(); i++) {
			if (addressListData.get(i).default_add == 1) {
				defaultBean = addressListData.get(i);
				break;
			}
		}
		if (defaultBean == null) {
			defaultBean = addressListData.get(0);
		}
		defaultAddress(defaultBean);
	}

	// //// = = = = = = = = = = = = = = = = 一下属于支付的流程
	private Intent mIntent = null;
	public static boolean isWXsuccess = false;
	private void successActivity(){
		ctx.startActivity(mIntent);
		isWXsuccess = false;
		finish();
	}
	/**
	 * 支付
	 */
	private void payMethod(BKBaseBean<BKOrderInfoBean> base) {
		mIntent = new Intent(ctx, PaySuccessAct.class);
		mIntent.putExtra("orderinfoBean", base.data);
		mIntent.putExtra("cost", "" + tv_total.getText().toString());
		try {
			mIntent.putExtra("count", "" + baseBean.data.list.get(0).countLocal);
		} catch (Exception e) {
			e.printStackTrace();
		}
		switch (payMode) {
		case 1:
			PaymentObject mPayObject = PaymentObject.getInstance(activity);
			mPayObject.setOnPayListener(new OnPayListener() {
				@Override
				public void success() {
					successActivity();
				}
				@Override
				public void failed() {
					// new AliPayPopWindow(ctx).show();
					// ctx.startActivity(mIntent);
					// finish();
				}
			});
			mPayObject.setOrderno(base.data.orderno);
			String money = base.data.total;
			if (IApplication.isPayTestMoney) {
				money = "0.01";
			}
			mPayObject.getOrderInfo("订单号:" + base.data.orderno, "订单详情:"
					+ base.data.toString(), money);
			mPayObject.Pay();
			break;
		case 2:
			// Toast.makeText(ctx, "没有集成微信支付", Toast.LENGTH_SHORT).show();
			PayWxObject mPayWxObject = new PayWxObject(ctx);
//			UnifiedOrderBean orderBean = new UnifiedOrderBean();
//			orderBean.body = "weixin" + base.data.branch;
//			orderBean.detail = "weixin details" ;
//			orderBean.notify_url = "http://121.40.35.3/test";
//			orderBean.out_trade_no = "" + base.data.orderno;
//			orderBean.spbill_create_ip = "127.0.0.1";
//			// orderBean.total_fee = Float.valueOf(base.data.total).intValue();
//			orderBean.total_fee = 1;
//
//			mPayWxObject.buildProductArgs(orderBean);
//			mPayWxObject.startPay();
			if (!TextUtils.isEmpty(base.data.prepay_id)) {
				mPayWxObject.genPayReq(base.data.prepay_id);
			}else{
				Toast.makeText(ctx, "没有获取prepay_id", Toast.LENGTH_SHORT).show();
			}
			break;
		case 3:
			UPPay mUpPay = new UPPay(activity);
			if (!TextUtils.isEmpty(base.data.tn)) {
				mUpPay.pay(base.data.tn);
			}else{
				Toast.makeText(ctx, "没有获取tn码", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 5) {
			if (resultCode == 2) {
				isSelected = true;
				BKAddressResultBean bean1 = (BKAddressResultBean) data
						.getSerializableExtra("bean");
				defaultAddress(bean1);
			}
		} else {
			/*************************************************
			 * 步骤3：处理银联手机支付控件返回的支付结果
			 ************************************************/
			if (data == null) {
				return;
			}
			String msg = "";
			/*
			 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
			 */
			String str = data.getExtras().getString("pay_result");
			if (str.equalsIgnoreCase("success")) {
				// msg = "支付成功！";
				ctx.startActivity(mIntent);
				finish();
			} else if (str.equalsIgnoreCase("fail")) {
				msg = "支付失败！";
			} else if (str.equalsIgnoreCase("cancel")) {
				msg = "用户取消了支付";
			}
			Toast.makeText(ctx, ""+msg, Toast.LENGTH_SHORT).show();
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			builder.setTitle("支付结果通知");
//			builder.setMessage(msg);
//			builder.setInverseBackgroundForced(true);
//			// builder.setCustomTitle();
//			builder.setNegativeButton("确定",
//					new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.dismiss();
//						}
//					});
//			builder.create().show();
		}
	}

}
